package indi.liangli.discovery;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

@Service
public class ServiceDisCoveryZkImpl implements IServiceDiscovery{
    //定义服务的地址
    List<String> serviceAddressList =new ArrayList<>();

    //创建curaotr
    CuratorFramework curatorFramework = null;
    {
        //创建会话超时事件为5秒，重试3次的衰减重试
        curatorFramework = CuratorFrameworkFactory.builder().sessionTimeoutMs(5000).
                connectString(ZKConfig.CONNECT_STR).retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("registry")
                .build();
        //启动zk客户端
        curatorFramework.start();


    }

    /**
     * 服务的发现，并通过负载均衡算法返回一个可用的服务
     * @param serviceName 服务的名称
     * @return
     */
    @Override
    public String discovery(String serviceName) {
        String servicePath = "/"+serviceName;
        if(serviceAddressList.isEmpty()){
            try {
                //获取服务所有地址
                serviceAddressList = curatorFramework.getChildren().forPath(servicePath);
                //注册节点的事件监听
                registryWachter(servicePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //准备负载均衡调用 定义一个策略对象
        //这里可以根据配置文件的策略来选择使用那个算法
        LoadBanlanceStrategy loadBanlanceStrategy = new RandomLoadBanlanceImpl();
        return loadBanlanceStrategy.selectHost(serviceAddressList);
    }

    private void registryWachter(String path) throws Exception {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework,path,true);

        PathChildrenCacheListener pathChildrenCacheListener = (curator,event) ->{
            //节点发生变化
            System.out.println(event.getType()+" -->"+event.getData().getPath());
            serviceAddressList = curator.getChildren().forPath(path);
        };

        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        pathChildrenCache.start();
    }
}
